<template>
  <div class="forget-container">
    <div v-if="!isSuccess">
      <h3 class="forget-title">重置密码</h3>
      <el-form class="forget-form" :model="resetForm" :rules="resetRules" ref="resetFormRef" size="large">
        <el-form-item label="" prop="account">
          <el-input v-model="resetForm.account" placeholder="请输入绑定的手机号" @blur="validateAccount" />
        </el-form-item>
        
        <el-form-item v-if="accountExists" label="" prop="code">
          <GetVarCode v-model="resetForm.code" :phone="resetForm.account" />
        </el-form-item>

        <el-form-item label="" prop="newPassword">
          <el-popover
            placement="bottom"
            :width="350"
            :visible="showTip"
          >
          <template #reference>
            <el-input type="password" v-model="resetForm.newPassword" placeholder="请输入新密码" show-password @focus="showTip = true" @blur="showTip = false" @input="validateNewPass" />
          </template>
          <div class="warn-content">
            <ul>
              <li>
                <el-icon class="iconfont correct" v-if="warnNewFlag.notIncludeAccount"><Check /></el-icon>
                <el-icon class="iconfont error" v-if="!warnNewFlag.notIncludeAccount"><Close /></el-icon>
                <span>密码不能包含账号</span>
              </li>
              <li>
                <el-icon class="iconfont correct" v-if="warnNewFlag.inputLength"><Check /></el-icon>
                <el-icon class="iconfont error" v-if="!warnNewFlag.inputLength"><Close /></el-icon>
                <span>密码长度大于等于8位</span>
              </li>
              <li>
                <el-icon class="iconfont correct" v-if="warnNewFlag.complexityRequirement"><Check /></el-icon>
                <el-icon class="iconfont error" v-if="!warnNewFlag.complexityRequirement"><Close /></el-icon>
                <span>必须同时包含大写字母、小写字母、数字、特殊字符中的三者</span>
              </li>
            </ul>
          </div>
          </el-popover>
        </el-form-item>

        <el-form-item label="" prop="confirmNewPassword">
          <el-input type="password" v-model="resetForm.confirmNewPassword" show-password placeholder="请再次输入新密码" />
        </el-form-item>
        <el-form-item class="forget-footer">
          <el-button type="primary" size="large" @click="handleSubmit(resetFormRef)" class="reset-btn">重置密码</el-button>
          <el-button link type="primary" @click="router.push('/login/index')" class="login-btn">已有帐号？去登录</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="reset-success" v-else>
      <div class="success-icon">
        <el-icon><Check /></el-icon>
      </div>
      <h3>重置成功</h3>
      <p>密码重置成功，请牢记您的密码</p>
      <el-button class="re-login-btn" type="primary" @click="returnLogin">重新登录</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { detectionAccount, resetPasswordByCode } from '@/api/user'
import { ElMessage } from 'element-plus'
import { Check, Close } from '@element-plus/icons-vue'
import GetVarCode from './components/GetVarCode'

const router = useRouter()
const resetFormRef = ref()
const isSuccess = ref(false)
const accountExists = ref(false)
const showTip = ref(false)

const resetForm = reactive({
  account: '',
  code: '',
  newPassword: '',
  confirmNewPassword: '',
})

// 密码校验标识
const warnNewFlag = reactive({
  notIncludeAccount: false,
  inputLength: false,
  complexityRequirement: false
})

// 校验账号
const validateAccount = async () => {
  if (!resetForm.account) {
    ElMessage.error('请输入账号!')
    return false
  }

  try {
    const res = await detectionAccount({ account: resetForm.account })
    if (res.data.is_exist === 1) {
      accountExists.value = true
      return true
    } else {
      ElMessage.error('账号不存在，请重新输入')
      accountExists.value = false
      return false
    }
  } catch (error) {
    console.error(error)
    return false
  }
}

// 新密码验证
const validateNewPass = value => {
  if (value) {
    warnNewFlag.notIncludeAccount = !value.toLowerCase().includes(resetForm.account.toLowerCase())
    warnNewFlag.inputLength = value.length >= 8

    const hasUpperCase = /[A-Z]/.test(value)
    const hasLowerCase = /[a-z]/.test(value)
    const hasNumbers = /[0-9]/.test(value)
    const hasSpecialChar = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(value)
    
    const conditions = [hasUpperCase, hasLowerCase, hasNumbers, hasSpecialChar]
    const metConditions = conditions.filter(condition => condition).length
    
    warnNewFlag.complexityRequirement = metConditions >= 3
  } else {
    warnNewFlag.notIncludeAccount = false
    warnNewFlag.inputLength = false
    warnNewFlag.complexityRequirement = false
  }
}

// 表单验证规则
const resetRules = {
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!warnNewFlag.notIncludeAccount || !warnNewFlag.inputLength || !warnNewFlag.complexityRequirement) {
          callback(new Error('请按照密码规则设置密码'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  confirmNewPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== resetForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 提交表单
const handleSubmit = async (formEl) => {
  if (!formEl) return
  
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        await resetPasswordByCode({
          account: resetForm.account,
          code: resetForm.code,
          newPassword: resetForm.newPassword,
          confirmNewPassword: resetForm.confirmNewPassword
        })
        isSuccess.value = true
      } catch (error) {
        console.error(error)
      }
    }
  })
}

const returnLogin = () => {
  router.push({ path: '/login' })
}
</script>

<style lang="scss" scoped>
.forget-container {
  width: 400px;
  .forget-title {
    font-size: 20px;
    font-weight: 600;
    text-align: center;
    margin-bottom: 20px;
  }
  .forget-form {
    .el-form-item--large:not(:last-child) {
      margin-bottom: 18px;
      .el-input--large {
        --el-input-height: 50px;
      }
    }
  }

  .forget-footer {
    display: flex;
    justify-content: space-between;
    .reset-btn {
      flex: 1;
    }
    .login-btn {
      min-width: 140px;
      font-size: 14px;
    }
  }

  .reset-success {
    width: 350px;
    margin: 40px auto 0;
    text-align: center;

    .success-icon {
      height: 60px;
      width: 60px;
      border-radius: 50%;
      background-color: #2cbf77;
      margin: 0 auto;
      display: flex;
      justify-content: center;
      align-items: center;

      i {
        font-size: 40px;
        color: $white;
      }
    }

    h3 {
      font-size: 20px;
      font-weight: normal;
      margin: 10px 0 5px;
    }

    p {
      color: $black_tips;
      font-size: 14px;
    }

    .re-login-btn {
      height: 50px;
      width: 100%;
      margin-top: 40px;
    }
  }
}

::v-deep .el-form-item__error:before {
  display: none !important;
}
</style>

<style>
.warn-content {
  background-color: #ffffff;
  border-radius: 4px;
  box-sizing: border-box;

  ul {
    list-style: none;
    margin: 0;
    padding: 0;
  }

  li {
    margin: 8px 0;
    
    .correct {
      color: #2cbf77;
    }
    .error {
      color: #ff5240;
    }
    
    span {
      margin-left: 6px;
    }
  }
}
</style>